#include "LockFreeQueue.h"
#include <iostream>
#include <vector> // for vector
#include <queue> // for queue
#include <thread> // for thread
#include <mutex> // for mutex
using namespace std;

// 测试无锁队列
void test1() {
    LockFreeQueue<size_t> lq;
    atomic<size_t> n(100000);

    size_t cost_time = 0;
    vector<thread> threads;
    // 创建3个子线程
    for (int i = 0; i < 3; ++i) {
        threads.push_back(thread([&](){
            size_t begin = 0, end = 0;
            begin = clock();
            for (size_t j = 0; j < n; ++j) {
                lq.enQueue(j);
            }
            end = clock();
            cost_time += (end - begin);
        }));
    }

    for (auto& e : threads) {
        e.join();
    }

    cout << "无锁队列花费时间：" << cost_time << endl;

}

// 测试有锁队列
mutex mx;
void test2() {
    queue<size_t> q;
    atomic<size_t> n(100000);

    size_t cost_time = 0;
    vector<thread> threads;
    // 创建3个子线程
    for (int i = 0; i < 3; ++i) {
        threads.push_back(thread([&](){
            size_t begin = 0, end = 0;
            begin = clock();
            for (size_t j = 0; j < n; ++j) {
                mx.lock();
                q.push(j);
                mx.unlock();
            }
            end = clock();
            cost_time += (end - begin);
        }));
    }

    for (auto& e : threads) {
        e.join();
    }

    cout << "有锁队列花费时间：" << cost_time << endl;

}

int main(void)
{
    test1();
    test2();
    return 0;
}

